package crawler;

import java.util.Arrays;
import java.util.List;

import parser.ParserAnnotation;
import parser.ParserPipeline;
import twitter4j.Status;
import twitter4j.StatusDeletionNotice;
import twitter4j.StatusListener;
import twitter4j.TwitterStream;
import twitter4j.TwitterStreamFactory;
import twitter4j.auth.BasicAuthorization;
import asa.PostBucket;

import forum.ForumFactory;
import forum.ForumPost;

public class TwitterCrawler extends Crawler {
	private TwitterStream twitterStream;

	public TwitterCrawler(ForumFactory fac, ParserPipeline pp,
			PostBucket crawlerBucket) throws Exception {
		super("Twitter", fac, pp, crawlerBucket);
	}

	@Override
	public void run() {
		StatusListener listener = new StatusListener() {
			public void onStatus(Status status) {
				ParserAnnotation pa = pp.make(status.getText());
				pa.setSkipSentDetection(true);
				String title = status.getUser().getScreenName();
				String poster = status.getUser().getName();
				ForumPost post = fac.makePost(title, pa, "Twitter", poster,
						"http://www.twitter.com/" + status.getUser().getScreenName());
				fac.makeSent(pa.getDocument(), post);
				try {
					crawlerBucket.addPost(Arrays.asList(post));
				} catch (InterruptedException e) {
					try {
						close();
					} catch (Exception e1) {
						System.err.println("Error closing twitter...");
						e1.printStackTrace();
					}
				}
			}

			public void onDeletionNotice(
					StatusDeletionNotice statusDeletionNotice) {
			}

			public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
			}

			public void onException(Exception ex) {
				ex.printStackTrace();
			}

			public void onScrubGeo(long arg0, long arg1) {
			}
		};
		BasicAuthorization ba = new BasicAuthorization("ASAQV",
				"thisisnottheway");
		twitterStream = new TwitterStreamFactory().getInstance(ba);
		twitterStream.addListener(listener);
		twitterStream.sample();
	}

	@Override
	// Not used because overridden run method
	protected List<ForumPost> crawl() throws Exception {
		return null;
	}

	@Override
	public void close() throws Exception {
		twitterStream.cleanUp();
	}

	@Override
	public boolean canCrawl() {
		return true;
	}
}
